package com.share.shareplatform.shareorder.service.impl;


import com.share.shareplatform.common.state.OrderState;
import com.share.shareplatform.pojo.Goods;
import com.share.shareplatform.pojo.Order;
import com.share.shareplatform.pojo.exception.LogicException;
import com.share.shareplatform.shareorder.dao.OrderDao;
import com.share.shareplatform.shareorder.service.OrderService;
import com.share.shareplatform.shareorder.service.feign.GoodsService;
import com.share.shareplatform.util.AuthorityUtil;
import com.share.shareplatform.util.Result;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("orderService")
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public Long addOne(Order order) {
        return orderDao.addOne(order);
    }

    @Override
    public Integer updateOne(Order order) {
        return orderDao.updateOne(order);
    }

    @Override
    public Integer deleteOneById(Long id) {
        return orderDao.deleteOneById(id);
    }

    @Override
    public Integer deleteAllByIds(Long[] ids) {
        return orderDao.deleteAllByIds(ids);
    }

    @Override
    public Integer deleteAllSafeByIds(List<Long> ids) throws LogicException {
        Long userId = AuthorityUtil.getUserId();
        for(Long id:ids){
            Order order = orderDao.findOneSafeById(id);
            if(order==null){
                throw new LogicException("删除失败，订单已不存在");
            }
            if(order.getUserId()!=userId){
                throw new LogicException("该订单不属于你，无法删除");
            }
            if(!Order.isDeletable(order)){
                throw new LogicException("该订单还在进行中，无法被删除");
            }
            orderDao.deleteOneById(order.getId());
        }
        return 1;
    }

    @Override
    public Order findOneById(Long id) {
        return orderDao.findOneById(id);
    }

    @Override
    public List<Order> findAllByUserId(Long id) {
        return orderDao.findAllByUserId(id);
    }

    @Override
    public List<Order> findAllByUserIdAndState(Long id, String state) {
        return orderDao.findAllByUserIdAndState(id,state);
    }

    @Override
    public List<Order> findAllByUserIdAndType(Long id, String state) {
        if(state.equals(OrderState.ALL.getState())){
            return orderDao.findAllByUserId(id);
        }
        return orderDao.findAllByUserIdAndState(id,state);
    }

    @Override
    public Integer updatePayOrders(List<Order> orderList) throws LogicException {
        return null;
    }

    @Override
    @GlobalTransactional(name = "order_pay",rollbackFor = Exception.class)
    @Transactional
    public Integer globalUpdateAllPaymentStateByIds(List<Long> orderList)  {

        Integer flag = orderDao.updateAllPaymentStateByIds(OrderState.WAITING_FOR_PAYMENT.getState(),OrderState.WAITING_FOR_SENDING.getState(), orderList);
        if(flag!=orderList.size()){
            throw new LogicException("部分订单已经付过款，请联系客服");
        }
        List<Order> orders = orderDao.findAllById(orderList);

        StringBuilder s=new StringBuilder();
        for(Order order:orders){
            s.append(order.getGoodsId()+"-"+order.getBuyNumber()+",");
        }
        if(s.length()==0){
            throw new LogicException("没有订单");
        }
        s.deleteCharAt(s.length()-1);
        asyncUpdate(s.toString());
        return 1;
    }


    //异步方式，消息队列
    public void asyncUpdate(String message){
        rabbitTemplate.convertAndSend("repertory",message);
    }

    //同步方式，远程调度
    public void syncUpdate(String s){
        Result result = goodsService.updateAllRepertory(s.toString());
        if(result.getCode()!=200){
            throw new LogicException("库存删减失败");
        }
    }

    @Override
    public List<Order> findAllByGoodsList(Long id, List<Goods> goods) {
        return orderDao.findAllByGoodsList(id,goods);
    }

    @Override
    public List<Order> findAllById(List<Long> list) {
        return orderDao.findAllById(list);
    }


}
